package com.youlu.campus.service.jinshuju;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.UserPO;
import com.youlu.campus.entity.VO.req.ActivityQaInfoVO;
import com.youlu.campus.entity.VO.req.UserDoQaVO;
import com.youlu.campus.entity.jinshuju.JinUserParticipate;
import com.youlu.campus.entity.jinshuju.JinUserRank;
import com.youlu.campus.entity.jinshuju.dto.JinShuJuActivityProgressDTO;
import com.youlu.campus.entity.jinshuju.dto.JinShuJuQaInfo;
import com.youlu.campus.entity.jinshuju.dto.JinShuJuQaResultDTO;
import com.youlu.campus.entity.jinshuju.dto.JinShuJuUserTranscriptDTO;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.contest.QQMiniContestService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.vote.SimpleActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class JinShuJuQaService {

    @Autowired
    private ActivityService activityService;

    @Autowired
    private QQMiniContestService qqMiniContestService;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SimpleActivityService simpleActivityService;

    @Autowired
    private JinShuJuUserRankService jinShuJuUserRankService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String USER_SINGN_INFO_CACHE="jinshuju:user.mobile:%s:activity:%s";


    public void setCacheUserInfo(JinUserParticipate setCacheJinUserParticipate){
        log.info("设置用户报名缓存 mobile:{}|activityId:{}",setCacheJinUserParticipate.getMobile(),setCacheJinUserParticipate.getActivityId());
        String key = String.format(USER_SINGN_INFO_CACHE, setCacheJinUserParticipate.getMobile(), setCacheJinUserParticipate.getActivityId());
        this.redisTemplate.delete(key);
        this.redisTemplate.opsForValue().set(key, JSON.toJSONString(setCacheJinUserParticipate),30L, TimeUnit.SECONDS);
    }

    private  JinUserParticipate getCacheUserByMobileAndActivityId(String mobile,String activityId){
        log.info("获取用户报名缓存 mobile:{}|activityId:{}",mobile, activityId);
        String key = String.format(USER_SINGN_INFO_CACHE, mobile, activityId);
        String userJson = this.redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(userJson)){
            return JSON.parseObject(userJson,JinUserParticipate.class);
        }
        return null;
    }


    public JinShuJuUserTranscriptDTO findUserQaTranscriptByActivityId(String activityId, UserPO currentUser) {
        List<String> fields = Lists.newArrayList("id", "restQaButtonUrl", "invitePublicistBottomImageUrl",
                "qaPassTips", "qaNotPassTips","hasShareDy","douYinUrl","hasShare");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        JinShuJuUserTranscriptDTO jinShuJuUserTranscript = new JinShuJuUserTranscriptDTO();
        jinShuJuUserTranscript.setInvitePublicistBottomImageUrl(activityInfo.getInvitePublicistBottomImageUrl());
        jinShuJuUserTranscript.setRestQaButtonUrl(activityInfo.getRestQaButtonUrl());
        jinShuJuUserTranscript.setQaNotPassTips(activityInfo.getQaNotPassTips());
        jinShuJuUserTranscript.setQaPassTips(activityInfo.getQaPassTips());
        jinShuJuUserTranscript.setHasShare(activityInfo.getHasShare());
        jinShuJuUserTranscript.setHasShareDy(activityInfo.getHasShareDy());
        jinShuJuUserTranscript.setDouYinUrl(activityInfo.getDouYinUrl());
        JinUserParticipate jinUserParticipate = getCacheUserByMobileAndActivityId(currentUser.getMobile(), activityId);
        if(Objects.isNull(jinUserParticipate)){
            Query query = new Query();
            query.addCriteria(Criteria.where("mobile").is(currentUser.getMobile()));
            query.addCriteria(Criteria.where("activityId").is(activityId));
            jinUserParticipate = this.mongoTemplate.findOne(query, JinUserParticipate.class);
        }
        if (Objects.nonNull(jinUserParticipate)) {
            jinShuJuUserTranscript.setName(jinUserParticipate.getName());
            jinShuJuUserTranscript.setUniversityName(jinUserParticipate.getUniversityName());
            jinShuJuUserTranscript.setScore(jinUserParticipate.getScore());
            jinShuJuUserTranscript.setQaTime(jinUserParticipate.getQaTime());
        }else{
            jinShuJuUserTranscript.setJoined(Boolean.FALSE);
        }
        ActivityQaInfo activityQaInfo = activityQaInfoService.findByActivityIdAndQaNumber(activityId,1);
        if (jinShuJuUserTranscript.getScore().compareTo(activityQaInfo.getPassQaScore()) == -1) {
            jinShuJuUserTranscript.setPassed(Boolean.FALSE);
        } else {
            jinShuJuUserTranscript.setPassed(Boolean.TRUE);
        }
        return jinShuJuUserTranscript;
    }


    public JinShuJuActivityProgressDTO findActivityProgressByActivityId(String activityId, UserPO currentUser) {
        List<String> fields = Lists.newArrayList("id", "name","inviteButtonImgUrl", "invitePopupButtonImgUrl",
                "invitePopupBackgroundImgUrl", "valueAlias", "hasIndexPopup",
                "indexPopupImage", "csDesc", "headerImageUrl", "footerImageUrl","inviteCountLimit","endTime",
                "stopDetail","userInfoBackgroundImgUrl","rankingBackgroundImgUrl","colorValueUserInfo","subButtonImgUrl","updateUserSignUp","hideEndTime","startTime","endTime","colorValueMenu");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            log.error(":>>> 活动:{} 不存在",activityId);
            throw new BusinessException("活动不存在");
        }
        JinShuJuActivityProgressDTO activityProgress = new JinShuJuActivityProgressDTO();
        activityProgress.setCsDesc(activityInfo.getCsDesc());
        activityProgress.setFooterImageUrl(activityInfo.getFooterImageUrl());
        activityProgress.setHasIndexPopup(activityInfo.getHasIndexPopup());
        activityProgress.setHeaderImageUrl(activityInfo.getHeaderImageUrl());
        activityProgress.setInviteButtonImgUrl(activityInfo.getInviteButtonImgUrl());
        activityProgress.setInvitePopupBackgroundImgUrl(activityInfo.getInvitePopupBackgroundImgUrl());
        activityProgress.setValueAlias(activityInfo.getValueAlias());
        activityProgress.setIndexPopupImage(activityInfo.getIndexPopupImage());
        activityProgress.setInvitePopupButtonImgUrl(activityInfo.getInvitePopupButtonImgUrl());
        activityProgress.setStatus(qqMiniContestService.getActivityStatus(activityInfo.getEndTime()));
        activityProgress.setStopDetail(activityInfo.getStopDetail());
        activityProgress.setActivityName(activityInfo.getName());
        activityProgress.setRankingBackgroundImgUrl(activityInfo.getRankingBackgroundImgUrl());
        activityProgress.setUserInfoBackgroundImgUrl(activityInfo.getUserInfoBackgroundImgUrl());
        activityProgress.setColorValueUserInfo(activityInfo.getColorValueUserInfo());
        activityProgress.setSubButtonImgUrl(activityInfo.getSubButtonImgUrl());
        activityProgress.setUpdateUserSignUp(activityInfo.getUpdateUserSignUp());
        Query query = new Query();
        query.addCriteria(Criteria.where("mobile").is(currentUser.getMobile()));
        query.addCriteria(Criteria.where("activityId").is(activityId));
        JinUserParticipate jinUserParticipate = this.mongoTemplate.findOne(query, JinUserParticipate.class);
        if (Objects.isNull(jinUserParticipate)) {
            log.error(":>>> 用户:{}  未报名活动:{}",currentUser.getMobile(),activityId);
            throw new BusinessException("对不起，该活动您未报名");
        }
        activityProgress.setScore(jinUserParticipate.getScore());
        activityProgress.setName(jinUserParticipate.getName());
        activityProgress.setUniversityName(jinUserParticipate.getUniversityName());
        activityProgress.setUniversityId(jinUserParticipate.getUniversityId());
        JinUserRank rank = jinShuJuUserRankService.findByUserId(activityId,currentUser.getId());
        if(rank!=null){
            activityProgress.setInviteNum(rank.getInviteNum());
            activityProgress.setInviteScore(rank.getScore());
            activityProgress.setShowRanking(rank.getInviteNum()>=activityInfo.getInviteCountLimit());
        }
        activityProgress.setStartTime(activityInfo.getStartTime());
        activityProgress.setEndTime(activityInfo.getEndTime());
        activityProgress.setHideEndTime(activityInfo.getHideEndTime());
        activityProgress.setColorValueMenu(activityInfo.getColorValueMenu());
        return activityProgress;
    }

    public JinShuJuQaResultDTO qaResultCommit(UserDoQaVO req) {
        Double score = activityService.computeQaScore(req);
        ActivityQaInfo activityQaInfo = activityQaInfoService.findOne(req.getActivityQaInfoId());
        //答题分数小于设置分数答题未过
        Boolean passed = Boolean.TRUE;
        if (score.compareTo(activityQaInfo.getPassQaScore()) == -1) {
            passed = Boolean.FALSE;
        }
        Date now = new Date();
        return JinShuJuQaResultDTO.builder().passed(passed).score(score).qaTime(now).build();
    }


    public JinShuJuQaInfo findQaInfoByActivityId(String activityId) {
        List<String> fields = Lists.newArrayList("id","name", "stop", "stopDetail",
                "endTime", "jinShuJuSignUpHomeTopUrl", "jinShuJuSignUpBottomUrl", "qaNextButtonUrl");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        ActivityQaInfo activityQaInfo = activityQaInfoService.findByActivityIdAndQaNumber(activityId,1);
        ActivityQaInfoVO req = new ActivityQaInfoVO();
        req.setActivityId(activityId);
        req.setNo(1);
        req.setActivityQaInfoId(activityQaInfo.getId());
        List<ActivityQaInfoVO> qaInfoList = activityService.getQa(req);
        JinShuJuQaInfo jinShuJuQaInfo = new JinShuJuQaInfo();
        jinShuJuQaInfo.setStop(activityInfo.getStop());
        jinShuJuQaInfo.setStopDetail(activityInfo.getStopDetail());
        jinShuJuQaInfo.setStatus(qqMiniContestService.getActivityStatus(activityInfo.getEndTime()));
        jinShuJuQaInfo.setQaInfoList(qaInfoList);
        jinShuJuQaInfo.setJinShuJuSignUpHomeTopUrl(activityInfo.getJinShuJuSignUpHomeTopUrl());
        jinShuJuQaInfo.setJinShuJuSignUpBottomUrl(activityInfo.getJinShuJuSignUpBottomUrl());
        jinShuJuQaInfo.setQaNextButtonUrl(activityInfo.getQaNextButtonUrl());
        jinShuJuQaInfo.setActivityQaInfoId(activityQaInfo.getId());
        jinShuJuQaInfo.setActivityName(activityInfo.getName());
        return jinShuJuQaInfo;
    }
}
